package com.csx.micrometer.invoke.context.feign;

import com.csx.micrometer.common.util.MapUtil;
import com.csx.micrometer.invoke.context.MicrometerRequest;
import feign.Request;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/12/3 17:51
 */
public class MicrometerFeignRequest extends MicrometerRequest {

    private volatile Map<String, String> singleValueHeader;

    public MicrometerFeignRequest(Request originRequest) {
        super(originRequest);
    }

    private Map<String, String> toSingleValueHeaders() {
        Map<String, Collection<String>> headers = getOriginRequest().headers();
        return MapUtil.multiValueMapToSingleValue(headers, new LinkedCaseInsensitiveMap<>());
    }

    @Override
    public String getHeader(String name) {
        Collection<String> headers = getOriginRequest().headers().get(name);
        if(CollectionUtils.isEmpty(headers)) {
            return null;
        }
        return new ArrayList<>(headers).get(0);
    }

    @Override
    public String getRequestURL() {
        return getOriginRequest().url();
    }

    @Override
    public String getRequestURI() {
        String url = getOriginRequest().url();
        // TODO 转换为URI
        return url;
    }

    @Override
    public String getMethod() {
        return getOriginRequest().httpMethod().toString();
    }

    @Override
    public List<String> getHeaders(String name) {
        Collection<String> headers = getOriginRequest().headers().get(name);
        return new ArrayList<>(headers);
    }

    @Override
    public Map<String, String> getSingleValueHeaders() {
        if(singleValueHeader == null) {
            this.singleValueHeader = toSingleValueHeaders();
        }
        return singleValueHeader;
    }

    @Override
    public String getFirstHeader(String name) {
        return getSingleValueHeaders().get(name);
    }

    @Override
    public Request getOriginRequest() {
        return (Request) super.getOriginRequest();
    }
}
